﻿using NDK.Motion.MachineManager;
using NDK.Motion.MachineResources;
using NDK.Motion.Properties;
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;

namespace NDK.Motion.Frm
{
    public partial class Frm_AxisStatus : Form
    {
        private static log4net.ILog traceLogger = log4net.LogManager.GetLogger("Frm_AxisStatus");
        public Frm_AxisStatus()
        {
            InitializeComponent();
            dgv_AxisStatus.AutoGenerateColumns = false;
            foreach (var axis in MachineDataManager.Instance.AxisList)
            {
                if (axis != null)
                {
                    if (!cb_AxisId.Items.Contains(axis.AxisID))
                    {
                        cb_AxisId.Items.Add(axis.AxisID);
                    }
                    if (!cb_AxisName.Items.Contains(axis.Name))
                    {
                        cb_AxisName.Items.Add(axis.Name);
                    }
                }
            }
        }

        /// <summary>
        /// 是否实时监控DI状态
        /// </summary>
        public bool isMonitoring = false;
        private static Frm_AxisStatus _instance;
        private static readonly object singletonLock = new object();
        public static Frm_AxisStatus Instance
        {
            get
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null || _instance.IsDisposed)
                        {
                            _instance = new Frm_AxisStatus();
                        }
                    }
                }
                return _instance;
            }
        }
        private void Frm_AxisStatus_Load(object sender, EventArgs e)
        {
            dgv_AxisStatus.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);
            backgroundWorker1.RunWorkerAsync();
        }


        private void btn_Find_BtnClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cb_AxisName.Text.Trim()))
            {
                dgv_AxisStatus.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList.FindAll(i => i.Name.Contains(cb_AxisName.Text.Trim())));
                return;
            }
            if (!string.IsNullOrEmpty(cb_AxisId.Text.Trim()))
            {
                dgv_AxisStatus.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList.FindAll(i => i.AxisID.ToString() == cb_AxisId.Text.Trim()));
            }
            if (string.IsNullOrEmpty(cb_AxisName.Text.Trim()) && string.IsNullOrEmpty(cb_AxisId.Text.Trim()))
            {
                dgv_AxisStatus.DataSource = new BindingList<Axis>(MachineDataManager.Instance.AxisList);
            }
        }

        private void ckb_Monitoring_CheckedChanged(object sender, EventArgs e)
        {
            if (ckb_Monitoring.CheckState == CheckState.Checked)
            {
                isMonitoring = true;
            }
            else
            {
                isMonitoring = false;
            }
        }
        /// <summary>
        /// 实时监控DI状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                if (isMonitoring)
                {
                    for (int rowIndex = 0; rowIndex < dgv_AxisStatus.Rows.Count; rowIndex++)
                    {
                        try
                        {
                            //DataGridView处于编辑状态时，不检查状态
                            if (dgv_AxisStatus.Rows[rowIndex].IsNewRow) break;
                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cName"].IsInEditMode) break;
                            //获取当前行的
                            string name = dgv_AxisStatus.Rows[rowIndex].Cells["cName"].Value.ToString();
                            string axisId = dgv_AxisStatus.Rows[rowIndex].Cells["cAxisId"].Value.ToString();

                            Axis axis = MachineDataManager.Instance.AxisList.Find(i => i.AxisID.ToString() == axisId && i.Name.ToString() == name);
                            //得到轴状态，更新界面状态
                            bool alarm = axis.GetAlarm();
                            bool pel = axis.GetPEL();
                            bool org = axis.GetORG();
                            bool mel = axis.GetMEL();
                            bool serveOn = axis.GetServoOn();
                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cALM"].Tag?.ToString().ToUpper() != alarm.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cALM"].Value = (alarm == true) ? Resources.LightOn : Resources.LightOff;
                                dgv_AxisStatus.Rows[rowIndex].Cells["cALM"].Tag = alarm;
                            }


                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cPEL"].Tag?.ToString().ToUpper() != pel.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cPEL"].Value = (pel == true) ? Resources.LightOn : Resources.LightOff;
                                dgv_AxisStatus.Rows[rowIndex].Cells["cPEL"].Tag = pel;
                            }


                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cORG"].Tag?.ToString().ToUpper() != org.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cORG"].Value = (org == true) ? Resources.LightOn : Resources.LightOff;
                                dgv_AxisStatus.Rows[rowIndex].Cells["cORG"].Tag = org;
                            }


                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cMEL"].Tag?.ToString().ToUpper() != mel.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cMEL"].Value = (mel == true) ? Resources.LightOn : Resources.LightOff;
                                dgv_AxisStatus.Rows[rowIndex].Cells["cMEL"].Tag = mel;
                            }


                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cServeOnStatus"].Tag?.ToString().ToUpper() != serveOn.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cServeOnStatus"].Value = (serveOn == true) ? Resources.LightOn : Resources.LightOff;
                                dgv_AxisStatus.Rows[rowIndex].Cells["cServeOnStatus"].Tag = serveOn;
                            }


                            var pos = axis.GetPos();
                            if (dgv_AxisStatus.Rows[rowIndex].Cells["cCurPos"].Tag?.ToString().ToUpper() != pos.ToString().ToUpper())
                            {
                                //状态没有发生变化,不设置
                                dgv_AxisStatus.Rows[rowIndex].Cells["cCurPos"].Value = pos.ToString();
                                dgv_AxisStatus.Rows[rowIndex].Cells["cCurPos"].Tag = pos;
                            }
                        }
                        catch (Exception ex)
                        {
                            traceLogger.Error(ex.StackTrace);
                        }
                        Application.DoEvents();
                    }
                }
                Thread.Sleep(100);
                Application.DoEvents();
            }
        }

        private void dgv_AxisStatus_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }




    }
}
